/***********************************************************
**  File Name:  hal_iic.h
**  Brief:      Standard IIC BUS Functions
**  MCU:        CC2530
**  Date:       2014-7-17 10:13:39
**  Update:     add iic.c to Z-Stack
**  Author:     GuoZhenjiang <zhenjiang.guo@sunplusapp.com>
**                           <guo_zhen_jiang@163.com>
***********************************************************/

#ifndef __IIC_H__
#define __IIC_H__

#include "hal_io.h"
#include "hal_types.h"
#include "hal_defs.h"

// IIC Port
#define IIC_SCL_PORT    P0
#define IIC_SDA_PORT    P0
#define IIC_SCL_GROUP   0
#define IIC_SDA_GROUP   0
#define IIC_SCL_BN      0
#define IIC_SDA_BN      1

// IIC clock cycle control
#define IIC_SCK_DELAY   iicSckDelay(5)  // May need to modify for different IIC devices.

// IIC SDA Pin direction control
#define IIC_SCL_OUT     HalIOSetOutput(IIC_SCL_GROUP, IIC_SCL_BN)
#define IIC_SDA_OUT     HalIOSetOutput(IIC_SDA_GROUP, IIC_SDA_BN)
#define IIC_SDA_IN      HalIOSetInput(IIC_SDA_GROUP, IIC_SDA_BN, Pull_Up)

// Read IIC SDA Pin(H/L: 1/0)
#define IIC_RD_SDA      ((IIC_SDA_PORT & BIT_1(IIC_SDA_BN)) >> (IIC_SDA_BN))

// IIC Pin IO Level control
#define IIC_SET_SCL     IIC_SCL_PORT |= BIT_1(IIC_SCL_BN)
#define IIC_SET_SDA     IIC_SDA_PORT |= BIT_1(IIC_SDA_BN)

#define IIC_CLR_SCL     IIC_SCL_PORT &= BIT_0(IIC_SCL_BN)
#define IIC_CLR_SDA     IIC_SDA_PORT &= BIT_0(IIC_SDA_BN)


#define IIC_ACK     0   // response correct
#define IIC_NOACK   1   // no response

#define IIC_W_ADDR(addr)    (addr & 0xFE)   // LSB is 0 when write
#define IIC_R_ADDR(addr)    (addr | 0x01)   // LSB is 1 when read

// IIC SCK cycle delay time
extern void iicSckDelay(uint16 t);
// IIC port init
extern void iicInit(void);
// IIC ST(Start)
extern void iicStart(void);
// IIC SP(Stop)
extern void iicStop(void);
// IIC send Ack(Acknolwledge)
extern void iicSendAck(uint8 ack);
// IIC receive Ack
extern uint8 iicRecvAck(void);
// IIC send Byte
extern uint8 iicSendByte(uint8 byteDate);
// IIC read Byte
extern uint8 iicRecvByte(uint8 ack);
// IIC Write to address
extern uint8 iicWriteDev(uint8 devAddr);
// IIC Read from address
extern uint8 iicReadDev(uint8 devAddr);

#endif //__IIC_H__